package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: user1
 * date: 2022/3/14
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/","/index","index.html"})
    public String indexPage(Model model){
        //TODO 1、查出所有一级分类
        List<CategoryEntity> categoryEntities =  categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Object getCatalogJson(){
        Map<String, List<Catelog2Vo>>  map = categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public Object getHello(){
        RLock lock = redissonClient.getLock("my-lock");
        //1、加锁
        //1）、会实现自动续期，时间未30s，不用担心业务时间过长
        lock.lock(30, TimeUnit.SECONDS);
        try{
            System.out.println("加锁成功！执行业务。。。" + Thread.currentThread().getId());
            Thread.sleep(20000);
        }catch (Exception e){

        }finally {
            //解锁 解锁代码没有运行，是否会出现死锁
            System.out.println("解锁成功！" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    @ResponseBody
    @GetMapping("/write")
    public Object writeValue(){

        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = readWriteLock.writeLock();
        rLock.lock();
        try {
            s = UUID.randomUUID().toString();
            Thread.sleep(10000);
            stringRedisTemplate.opsForValue().set("writeValue",s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }


        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public  String readValue()
    {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        String s="";
        //加读锁
        RLock rLock=readWriteLock.readLock();
        rLock.lock();
        try{
            s=stringRedisTemplate.opsForValue().get("writeValue");
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            rLock.unlock();
        }

        return  s;
    }


    /**
     * 车库停车
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.acquire();
        boolean b = park.tryAcquire();

        return  "ok=>" + b;
    }

    /**
     * 车库停车
     */
    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();//释放一个

        return  "ok";
    }


    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();  //等待闭锁完成

        return  "放假了。。。";
    }


    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String lockDoor(@PathVariable("id") Long id)  {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();  //计数减一

        return  id + "班的走了。。。";
    }
}
